const {slugify} = require('transliteration');
const Base = require("../../admin/controller/base");


module.exports = class extends Base {

    async _initialize() {
        await super._initialize();
    }

    async indexAction() {
        this.assign({
            status: [{key: '0', title: '关闭'}, {key: '1', title: '开启'}]
        });
        await this.display('datacenter/mapmark/index');
    }

    // async updateAction() {
    //
    //     const id = this.query('id');
    //     const status = this.query('status');
    //     const ids = id.split(',');
    //
    //     for (let i in ids) {
    //         await this.mongoose('Mapmark').add({id: ids[i], status: status});
    //     }
    //
    //     this.success('', '保存成功');
    // }

    async tableAction() {

        const p = this.query('page') || 1;

        const id = this.post('id');
        const status = this.post('status');
        const keywords = this.post('keywords');

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (!think.isEmpty(keywords)) {
            queryParams = {
                $or: [
                    {title: {$regex: keywords, $options: "$i"}},
                    {address: {$regex: keywords, $options: "$i"}},
                    // {mobile: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (!think.isEmpty(status)) {
            queryParams = Object.assign(queryParams, {status: status});
        }

        //id属性要单独查找,不支持正则表达式
        if (!think.isEmpty(id)) {
            try {
                queryParams = {
                    _id: think.Mongoose.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.error(1001, '没找到符合条件的记录');
                return;
            }
        }

        // this.logger.debug(`search queryParams:${JSON.stringify(queryParams)}`);
        const pageSize = await this.mongoose('Config',{},'admin').C('LIST_ROWS');
        let pageEntity = await this.mongoose('Mapmark').findPage({
            page: p,
            pageSize: pageSize
        }, 'cover', queryParams, {}, {createdAt: 'desc'});

        this.assign({
            records: pageEntity.data,
            pager: super.ajaxPage(p, pageEntity.pagination.rowCount, pageEntity.pagination.pageSize)
        });
        await this.display('datacenter/mapmark/table');
    }

    async disableAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('Mapmark');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 0}).exec();
        }
        this.success('', '禁用成功');

    }

    async enableAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('Mapmark');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 1}).exec();
            //this.changeModelField('datacenter/datacenter/Administrator', i, 'status', 1);
        }
        this.success('', '开启成功');
    }

    async deleteAction() {
        const id = this.post('id');
        const ids = id.split(',');
        let Model = this.mongoose('Mapmark');
        for (const i of ids) {
            await Model.findByIdAndRemove(i).exec();
        }
        this.success('', '删除成功');
    }

    async addAction() {

        if (this.isPost) {

            let cover = this.post('cover');
            if (think.isEmpty(cover)) {
                cover = null;
            } else {
                try {
                    cover = think.Mongoose.mongoose.Types.ObjectId(cover);
                } catch (e) {
                    cover=null;
                    think.logger.error(e);
                }
            }

            let id = this.post('id');
            if (think.isEmpty(id)) {
                id = null;
            } else {
                try {
                    id = think.Mongoose.mongoose.Types.ObjectId(id);
                } catch (e) {
                    think.logger.error(e);
                }
            }

            let mapmark = {
                _id: id,
                title: this.post('title'),
                pinyin: slugify(this.post('title')),
                latitude: this.post('latitude'),
                longitude: this.post('longitude'),
                address: this.post('address'),
                cover: cover,
                tags: this.post('tags'),
                status: this.post('status')
            };

            if (think.isEmpty(id)) {
                delete mapmark['_id'];
            }


            think.logger.info(mapmark);

            const Model = this.mongoose('Mapmark');
            if (!think.isEmpty(id)) {
                await Model.findByIdAndUpdate(id, mapmark).exec();
                this.success('/datacenter/mapmark/index', '更新成功');
            } else {
                await Model.create(mapmark);
                this.success('/datacenter/mapmark/index', '创建成功');
            }

        } else {

            const id = this.query('id');
            if (!think.isEmpty(id)) {
                //查出关联的封面图片信息
                const mapmark = await this.mongoose('Mapmark').findOne({_id: id}).populate('cover');
                if (mapmark) {
                    this.assign({mapmark: mapmark});

                    await this.display('datacenter/mapmark/add');
                } else {
                    this.redirect('/datacenter/mapmark/index');
                }
            } else {
                await this.display('datacenter/mapmark/add');
            }
        }
    }
}
